package cn.iocoder.yudao.module.system.controller.admin.erp.customerinformation;

import cn.hutool.core.util.ObjectUtil;
import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.system.controller.admin.erp.customerinformation.vo.CustomerInformationPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.erp.customerinformation.vo.CustomerInformationRespVO;
import cn.iocoder.yudao.module.system.controller.admin.erp.customerinformation.vo.CustomerInformationSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.erp.customerinformation.CustomerInformationDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.framework.CommonConstant;
import cn.iocoder.yudao.module.system.service.erp.customerinformation.CustomerInformationService;
import cn.iocoder.yudao.module.system.service.erp.customermanage.CustomerManageService;
import cn.iocoder.yudao.module.system.service.erp.customermanage.CustomerManageServiceImpl;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import org.springframework.web.bind.annotation.*;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import jakarta.validation.*;
import jakarta.servlet.http.*;

import java.math.BigDecimal;
import java.util.*;
import java.io.IOException;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;
import static java.util.Arrays.asList;

@Tag(name = "管理后台 - 客户信息")
@RestController
@RequestMapping("/erp/customer-information")
@Validated
public class CustomerInformationController {

    @Resource
    private CustomerInformationService customerInformationService;
    @Resource
    private AdminUserService userService;
    @Resource
    private CustomerManageService customerManageService;


    @PostMapping("/create")
    @Operation(summary = "创建客户信息")
    @PreAuthorize("@ss.hasPermission('erp:customer-information:create')")
    public CommonResult<Long> createCustomerInformation(@Valid @RequestBody CustomerInformationSaveReqVO createReqVO) {
        BigDecimal deposit = createReqVO.getDeposit();
        if(ObjectUtil.isNotNull(deposit)&&deposit.scale()>4){
          throw exception(new ErrorCode(500,"押金最多不能超过4位小数"));
        }
        BigDecimal balancePayment = createReqVO.getBalancePayment();
        if(ObjectUtil.isNotNull(balancePayment)&&balancePayment.scale()>4){
            throw exception(new ErrorCode(500,"尾款最多不能超过4位小数"));
        }
        return success(customerInformationService.createCustomerInformation(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新客户信息")
    @PreAuthorize("@ss.hasPermission('erp:customer-information:update')")
    public CommonResult<Boolean> updateCustomerInformation(@Valid @RequestBody CustomerInformationSaveReqVO updateReqVO) {
        BigDecimal deposit = updateReqVO.getDeposit();
        if(ObjectUtil.isNotNull(deposit)&&deposit.scale()>4){
            throw exception(new ErrorCode(500,"押金最多不能超过4位小数"));
        }
        BigDecimal balancePayment = updateReqVO.getBalancePayment();
        if(ObjectUtil.isNotNull(balancePayment)&&balancePayment.scale()>4){
            throw exception(new ErrorCode(500,"尾款最多不能超过4位小数"));
        }


        customerInformationService.updateCustomerInformation(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除客户信息")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('erp:customer-information:delete')")
    public CommonResult<Boolean> deleteCustomerInformation(@RequestParam("id") Long id) {
        customerInformationService.deleteCustomerInformation(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得客户信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('erp:customer-information:query')")
    public CommonResult<CustomerInformationRespVO> getCustomerInformation(@RequestParam("id") Long id) {
        CustomerInformationRespVO customerInformation = BeanUtils.toBean(customerInformationService.getCustomerInformation(id), CustomerInformationRespVO.class);
        if(ObjectUtil.isNotNull(customerInformation)){
            AdminUserDO user = userService.getUser(customerInformation.getCustomerId());
            if (ObjectUtil.isNotNull(user)){
            customerInformation.setNickname(user.getNickname());
            }
        }
        return success(BeanUtils.toBean(customerInformation, CustomerInformationRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得客户信息分页")
    @PreAuthorize("@ss.hasPermission('erp:customer-information:query')")
    public CommonResult<PageResult<CustomerInformationRespVO>> getCustomerInformationPage(@Valid CustomerInformationPageReqVO pageReqVO) {
        Long loginUserId=SecurityFrameworkUtils.getLoginUserId();
        AdminUserDO user=userService.getUser(loginUserId);
        String roleCode=user.getRoleCode();
        PageResult<CustomerInformationRespVO> pageResult =new PageResult<>();
        if(ObjectUtil.equal(loginUserId,1L)||asList(CommonConstant.ERP_ADMIN,CommonConstant.ERP_SUPER_ADMIN).contains(roleCode)){
        List<Long>customerIds=new ArrayList<>();
        if(ObjectUtil.contains(CommonConstant.ERP_ADMIN,roleCode)){customerIds=customerManageService.getCustomerIds(loginUserId);}
        pageReqVO.setCustomerIds(customerIds);
        pageResult=BeanUtils.toBean(customerInformationService.getCustomerInformationPage(pageReqVO), CustomerInformationRespVO.class);
        if(!pageResult.getList().isEmpty()){
        Map<Long, AdminUserDO> userMap = userService.getUserMap(customerIds);
        pageResult.getList().forEach(e->{
        e.setNickname(userMap.get(e.getCustomerId()).getNickname());
        });}}
        return success(pageResult);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出客户信息 Excel")
    @PreAuthorize("@ss.hasPermission('erp:customer-information:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportCustomerInformationExcel(@Valid CustomerInformationPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<CustomerInformationDO> list = customerInformationService.getCustomerInformationPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "客户信息.xls", "数据", CustomerInformationRespVO.class,
                        BeanUtils.toBean(list, CustomerInformationRespVO.class));
    }

    @PutMapping("/customer-update")
    @Operation(summary = "更新客户信息")
    @PreAuthorize("@ss.hasPermission('erp:customer-information:update')")
    public CommonResult<Boolean> updateCustomerInformation2(@Valid @RequestBody CustomerInformationSaveReqVO updateReqVO) {
        BigDecimal deposit = updateReqVO.getDeposit();
        if(ObjectUtil.isNotNull(deposit)&&deposit.scale()>4){
            throw exception(new ErrorCode(500,"押金最多不能超过4位小数"));
        }
        BigDecimal balancePayment = updateReqVO.getBalancePayment();
        if(ObjectUtil.isNotNull(balancePayment)&&balancePayment.scale()>4){
            throw exception(new ErrorCode(500,"尾款最多不能超过4位小数"));
        }
        Long customerId = updateReqVO.getCustomerId();
        if(ObjectUtil.isNull(customerId)){
            throw exception(new ErrorCode(500,"客户id不能为空"));
        }
        AdminUserDO user = userService.getUser(customerId);
        if(ObjectUtil.isNull(user)){
            throw exception(new ErrorCode(500,"客户id不存在"));
        }
        CustomerInformationDO customerInformationDO = customerInformationService.byCustomerIdGetInformation(customerId);
        if(ObjectUtil.isNull(customerInformationDO)){
            updateReqVO.setId(null);
            customerInformationService.createCustomerInformation(updateReqVO);
        }else {
            updateReqVO.setId(customerInformationDO.getId());
            customerInformationService.updateCustomerInformation(updateReqVO);
        }
        return success(true);
    }

    @DeleteMapping("/customer-delete")
    @Operation(summary = "删除客户信息")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('erp:customer-information:delete')")
    public CommonResult<Boolean> deleteCustomerInformation2(@RequestParam("customerId") Long customerId) {
        customerInformationService.deleteCustomerInformation(customerId);
        return success(true);
    }

    @GetMapping("/customer-get")
    @Operation(summary = "获得客户信息")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('erp:customer-information:query')")
    public CommonResult<CustomerInformationRespVO> getCustomerInformationInfo(@RequestParam("customerId") Long customerId) {
        CustomerInformationRespVO customerInformation = BeanUtils.toBean(customerInformationService.byCustomerIdGetInformation(customerId), CustomerInformationRespVO.class);
        if(ObjectUtil.isNotNull(customerInformation)){
            AdminUserDO user = userService.getUser(customerInformation.getCustomerId());
            if (ObjectUtil.isNotNull(user)){
                customerInformation.setNickname(user.getNickname());
            }
        }
        return success(BeanUtils.toBean(customerInformation, CustomerInformationRespVO.class));
    }
}